package com.example.examwlxy.playwright;

import com.example.examwlxy.controller.BaseController;
import com.example.examwlxy.entity.AccountEntity;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SimpleTaskScheduler {

    /**
     * 在指定时间依次执行所有任务
     * @param runnables 任务列表
     * @param executeTime 执行时间（格式：2025/5/27 9:55）
     */
    public static void executeAtTime(List<Runnable> runnables, String executeTime,String number) {
        try {
            // 解析目标时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d H:mm");
            LocalDateTime targetTime = LocalDateTime.parse(executeTime, formatter);
            
            // 计算当前时间与目标时间的差值（毫秒）
            long delayMillis = calculateDelayMillis(targetTime);
            
            // 如果目标时间已过去，直接执行
            if (delayMillis <= 0) {
                System.out.println("目标时间已过去，立即执行任务");
                executeSequentially(runnables,number);
                return;
            }
            
            // 等待到指定时间
            System.out.printf("等待 %d 秒后开始执行任务...%n", delayMillis / 1000);
            Thread.sleep(delayMillis);
            
            // 依次执行所有任务
            executeSequentially(runnables,number);
            
        } catch (Exception e) {
            System.err.println("执行定时任务出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 计算当前时间到目标时间的延迟（毫秒）
    private static long calculateDelayMillis(LocalDateTime targetTime) {
        LocalDateTime now = LocalDateTime.now();
        long delaySeconds = 0;
        
        // 计算年差
        int years = targetTime.getYear() - now.getYear();
        if (years > 0) {
            delaySeconds += years * 365 * 24 * 60 * 60;
        }
        
        // 计算月差
        int months = targetTime.getMonthValue() - now.getMonthValue();
        if (months > 0) {
            delaySeconds += months * 30 * 24 * 60 * 60; // 简化计算，每月按30天
        }
        
        // 计算日差
        int days = targetTime.getDayOfMonth() - now.getDayOfMonth();
        if (days > 0) {
            delaySeconds += days * 24 * 60 * 60;
        }
        
        // 计算时差
        int hours = targetTime.getHour() - now.getHour();
        if (hours > 0) {
            delaySeconds += hours * 60 * 60;
        }
        
        // 计算分差
        int minutes = targetTime.getMinute() - now.getMinute();
        if (minutes > 0) {
            delaySeconds += minutes * 60;
        }
        
        // 转换为毫秒
        return delaySeconds * 1000;
    }
    
    // 依次执行所有任务
    private static void executeSequentially(List<Runnable> runnables,String number) {
        for (int i = 0; i < runnables.size(); i++) {
            try {
                System.out.printf("开始执行任务 %d/%d...%n", i + 1, runnables.size());
                for (int j = 0; j < Integer.parseInt(number); j++) {
                    runnables.get(i).run();
                }
                AccountEntity account = PlaywrightExample.accountList.get(i);

                PlaywrightExample.pageMaps.get(account.getAccount()).close();
                PlaywrightExample.pageMaps.remove(account.getAccount()) ;
                System.out.printf("任务 %d/%d 执行完成%n", i + 1, runnables.size());
                Thread.sleep(5000);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.printf("任务 %d/%d 执行失败: %s%n", i + 1, runnables.size(), e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        // 准备要执行的任务
        List<Runnable> tasks = Arrays.asList(
                () -> System.out.println("执行任务1: 登录系统"),
                () -> System.out.println("执行任务2: 加载考试页面"),
                () -> System.out.println("执行任务3: 提交答案"),
                () -> System.out.println("执行任务4: 保存成绩")
        );
        // 指定执行时间
        String executeTime = "2025/5/27 10:08";


    }
}
